package com.example.secondhandspringboot.controller;


import com.example.secondhandspringboot.context.BaseContext;
import com.example.secondhandspringboot.domain.dto.CommentsDTO;
import com.example.secondhandspringboot.domain.entity.Comments;
import com.example.secondhandspringboot.domain.vo.CommentsVO;
import com.example.secondhandspringboot.results.Result;
import com.example.secondhandspringboot.service.ICommentsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周在林
 * @since 2024-04-07
 */
@RestController
@RequestMapping("/comments")
@CrossOrigin
@Slf4j
@RequiredArgsConstructor
public class CommentsController {
    private final ICommentsService commentsService;

    /**
     * 发送评论
     * @param commentsDTO
     * @return
     */
    @PostMapping("/sendComments")
    public Result sendComments(@RequestBody CommentsDTO commentsDTO){
        log.info("用户评论:"+commentsDTO);
        Long userId = BaseContext.getCurrentId();
        if (userId==null){
            return Result.error("请先登录后评论");
        }
        Comments comment=new Comments();
        comment.setContent(commentsDTO.getContent());
        comment.setGoodsId(commentsDTO.getGoodsId());
        comment.setUserId(userId);
        comment.setCreateTime(LocalDateTime.now());
        //保存
        commentsService.save(comment);
        return Result.success();
    }

    /**
     * 获取评论
     * @param goodsId
     * @return
     */
    @GetMapping("/getComments")
    public Result<List<CommentsVO>> getComments(@RequestParam Long goodsId,@RequestParam("userId") Long sellerId){
        log.info("获取评论:"+goodsId+",sellerId"+sellerId);
        List<CommentsVO> commentsVOList=new ArrayList<>();
        if (goodsId!=null){
            commentsVOList = commentsService.getComments(goodsId,sellerId);
        }
        return Result.success(commentsVOList);
    }

    /**
     * 删除评论
     * @param commentsId
     * @return
     */
    @DeleteMapping
    public Result deleteComments(@RequestParam("id") Long commentsId){
        if (commentsId==null){
            return Result.error("删除失败");
        }
        boolean b = commentsService.removeById(commentsId);
        if (!b){
            return Result.error("删除失败");
        }
        return Result.success();
    }
}
